<?php

class OrderAction extends ActionBase {
	
	public $view;
	public $returnUrl;
	
	public function run($id) {
		$c = $this->controller;
		
		$model = Goods::model()->findByPk($id);
		if (empty(Yii::app()->adminUser->id)) {
			throw new CHttpException(404,'请先登录，在选购商品');
		}
		if (!$model->isBuyAble()) {
			throw new CHttpException(404,'请注册为普通用户，在进行选购商品');
		}
		if (!is_object($model)) {
			throw new CHttpException(404, '商品不存在');
//			throw new CHttpException(404, '商品未代理');
		}
		
		$data = array(
			'items' => array(
//				'related_id' => $model->related_id,
				'goods_id' => $model->id,
				'provider_id' => $model->provider_id,
//				'dealer_id' => $model->dealer_id,
				'item_price' =>$model->getTurnoverPrice(),
			),
		);
		$order = Order::createOrder($model->class_id, $data);
		$modelName = get_class($order);
		if (isset($_POST[$modelName]) && CDataToken::dataIsValid($_POST)) {
			$order->attributes = $_POST[$modelName];
			if ($order->save()) {
				CDataToken::useData($_POST, array(
					'id' => $order->id,
				));
				$c->redirect(array_merge($this->returnUrl,array('id'=>$order->id)));
			}
		} else if(isset($_POST[$modelName]) && !CDataToken::dataIsValid($_POST)) {
			$params = CDataToken::getDataParams($_POST);
			$c->redirect(array_merge($this->returnUrl,array('id'=>$params['id'])));
		}
		$c->render($this->view, array(
			'model' => $order,
		));
	}
}

?>